package com.itisyue.fun.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

public class HashUtil {
    public static void getHashCode( String s1, String s2, String algorithm) throws NoSuchAlgorithmException {
        //扩展⽀持的算法
        Security.addProvider(new BouncyCastleProvider());
        System.out.println("-----------------------获取的hashAlgorithm是："+algorithm);
        String hashAlgorithm = algorithm;
        //s1字符串的hashcode
        String resultStr1  = getDigestResult(s1,hashAlgorithm);
        //s2字符串的hashcode
        String resultStr2  = getDigestResult(s2,hashAlgorithm);
        //两个hashcode拼接字符串s3
        String s3 = resultStr1 + resultStr2;
        //s3的hashcode
        String resultStr3  = getDigestResult(s3,hashAlgorithm);
        System.out.println("---------------分割线------------------------");
        System.out.println("s1的hashcode为："+resultStr1);
        System.out.println("---------------------------------------------");
        System.out.println("s2的hashcode为："+resultStr2);
        System.out.println("---------------------------------------------");
        System.out.println("---------------------------------------------");
        /*System.out.println("s1+s2="+s3);*/
        System.out.println("拼接s1+s2的hashcode为："+resultStr3);
        System.out.println("hashcode长度为："+resultStr3.length());
    }
    private static String getDigestResult(String str, String hashAlgorithm){
        MessageDigest mDigest = null;
        try {
            mDigest = MessageDigest.getInstance(hashAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            System.out.println("系统算法不⽀持将默认为MD5！");
            try {
                mDigest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        mDigest.update(str.getBytes());
        BigInteger bigInt = new BigInteger(1, mDigest.digest());
        String resultStr = bigInt.toString(16);
        return resultStr;
    }

    public static void main(String[] args) throws  Exception{
        getHashCode("123","456","md5");
        getHashCode("456","123","md5");
    }
}
